<?php
namespace App\Http\Library;

use App\Http\Library\WeChat\MiniWeChat;
use App\Http\Response\ApiResponse;
use App\Models\User;
use App\Models\Oauth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserAuth extends ApiResponse
{
    /**
     * @var User|null
     */
    protected ?User $model = null;
    protected ?Request $request = null;

    /**
     * 初始化
     * @param Request $request
     * @param User $user
     */
    public function __construct(Request $request, User $user)
    {
        parent::__construct();
        $this->request = $request;
        $this->model = $user;
    }

    /**
     * 注册
     */
    public function register()
    {
        //注册事件
    }

    /**
     *
     * @param $username
     * @param $password
     * @return mixed
     */
    public function login($username,$password): mixed
    {
        $auth = $this->model->where('name', $username)->first();
        if (!$auth){
            return $this->error('找不到此用户！');
        }
        if (!Hash::check($password ,$auth->password)){
            return $this->error('密码不正确,请重试！');
        }
        if ($auth->status==1){
            return $this->error('此账号已被禁用,请联系管理员！');
        }
        $token = $auth->createToken('user')->plainTextToken;
        $userInfo = array_merge($auth->toArray(),['token'=>$token]);
        return $this->success('登陆成功')->data($userInfo);
    }


    /**
     * 微信登陆
     * @param array $post
     * @return UserAuth
     */
    public function weChatLogin(array $post = []): UserAuth
    {
        $app = MiniWeChat::instance();
        $res = $app->getCode($post['code']);
        if(isset($res['errcode'])){
            return $this->error('code ERROR！')->data($res);
        }
        $openid = $res['openid'];
        $session_key = $res['session_key'];
        $oauth = Oauth::findUser('wx_app',$openid);
        if ($oauth){
            $oauth->save();
            $user = $this->model->find($oauth['user_id']);
            if ($user->status==1){
                return $this->error('此账号已被禁用,请联系管理员！');
            }
            $token = $user->createToken('user')->plainTextToken;
            $userInfo = array_merge($user->toArray(),['token'=>$token,'session_key'=>$session_key]);
        }else{
            $userInfo = $this->model->weChatRegister($openid,$session_key,$post);
        }
        return $this->success('登陆成功')->data($userInfo);
    }

    /**
     * 获取用户信息
     * @return mixed
     */
    public function getUserInfo(): mixed
    {
        return $this->request->user();
    }

}
